package com.example.a828502.ormlite.bean;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.example.a828502.ormlite.R;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;


/**
 * Created by 828502 on 2016/5/10.
 */
public class DatabaseHelper  extends OrmLiteSqliteOpenHelper {
    private Context mContext;
    private static final String DB_NAME = "ormlite_test.db";
    private static final int DB_VERSION = 2;
    private static DatabaseHelper instance = null;

    /**
     * 对dao进行缓存
     */
    private Map<String, Dao> daoMaps = new HashMap<String, Dao>();

    private DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        this.mContext = context;
    }

    /**
     * 单例获取Helper
     * @param context
     * @return
     */
    public static synchronized DatabaseHelper getHelper(Context context){
        if (instance ==null){
            synchronized (DatabaseHelper.class){
                if (instance == null){
                    instance = new DatabaseHelper(context);
                    writeDatabaseToSqlite(context);
                }
            }
        }
        return instance;
    }

    /**
     * 获取dao
     *
     * @param clazz
     * @return
     * @throws SQLException
     */

    public synchronized Dao getDao(Class clazz) throws SQLException {
        Dao dao = null;
        String className = clazz.getSimpleName();
        if (daoMaps.containsKey(className)) {
            dao = daoMaps.get(className);
        } else {
            dao = super.getDao(clazz);
            daoMaps.put(className, dao);
        }
        return dao;
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {

    }
    @Override
    public void onUpgrade(SQLiteDatabase database,ConnectionSource connectionSource,int oldVersion, int newVersion){
        int upgradeVerson = oldVersion;
        if (1 == upgradeVerson){
            writeDatabaseToSqlite(mContext);
            upgradeVerson = 2;
        }
    }

    private synchronized static void writeDatabaseToSqlite(Context context) {
        context.deleteDatabase(DB_NAME);

        StringBuffer sdpath = new StringBuffer();
        sdpath.append("/data")
                .append(Environment.getDataDirectory().getAbsolutePath())
                .append('/').append("com.example.a828502.ormlite").append("/databases")
                .append('/').append(DB_NAME);
        String databasePath = sdpath.toString();
        int lastSlashIndex = databasePath.lastIndexOf('/');
        String directoryStr = databasePath.substring(0, lastSlashIndex);
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            File directory = new File(directoryStr);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            // 判断数据库文件是否存在，若不存在则执行导入，否则直接打开数据库
            if (!(new File(databasePath).exists())) {
                is = context.getResources().openRawResource(
                        R.raw.ormlite_test);

                fos = new FileOutputStream(databasePath);
                byte[] buffer = new byte[10000];
                int count = 0;
                while ((count = is.read(buffer)) > 0) {
                    fos.write(buffer, 0, count);
                }
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.close();
                }
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
